package com.yhgm.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yhgm.annotation.AuthCheck;
import com.yhgm.common.BaseResponse;
import com.yhgm.common.DeleteRequest;
import com.yhgm.common.ErrorCode;
import com.yhgm.common.ResultUtils;
import com.yhgm.constant.UserConstant;
import com.yhgm.exception.BusinessException;
import com.yhgm.exception.ThrowUtils;
import com.yhgm.model.dto.department.DepartmentAddRequest;
import com.yhgm.model.dto.department.DepartmentQueryRequest;
import com.yhgm.model.entity.Department;
import com.yhgm.model.entity.User;
import com.yhgm.model.vo.DepartmentVO;
import com.yhgm.model.vo.UserVO;
import com.yhgm.service.DepartmentService;
import com.yhgm.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author: yh
 * @Date: 2024/3/23
 */
@Slf4j
@RestController
@RequestMapping("/department")
public class DepartmentController {
    @Resource
    private DepartmentService departmentService;
    @Resource
    private UserService userService;

    /**
     * 新增部门
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addDepartment(@RequestBody DepartmentAddRequest departmentAddRequest) {
        if (departmentAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Department department = new Department();
        BeanUtils.copyProperties(departmentAddRequest, department);
        boolean result = departmentService.save(department);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(department.getId());
    }

    /**
     * 根据id获取部门信息（管理员）
     * @param id
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Department> getDepartmentById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Department department = departmentService.getById(id);
        ThrowUtils.throwIf(department == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(department);
    }

    /**
     * 根据id获取部门信息（脱敏）
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<DepartmentVO> getDepartmentVO(long id) {
        BaseResponse<Department> response = getDepartmentById(id);
        Department department = response.getData();
        return ResultUtils.success(departmentService.getDepartmentVO(department));

    }

    /**
     * 删除部门
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteDepartment(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = departmentService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 修改部门信息（管理员）
     * @param department
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateDepartmentBy(@RequestBody Department department) {
        if (department == null || department.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = departmentService.updateById(department);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取部门列表（仅管理员）
     * 返回的是当前部门及其下面的所有子部门
     * @param departmentQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Department>> listDepartmentByPage(@RequestBody DepartmentQueryRequest departmentQueryRequest) {
        long current = departmentQueryRequest.getCurrent();
        long size = departmentQueryRequest.getPageSize();
        log.info("参数：" + departmentQueryRequest);
        Page<Department> departmentPage = departmentService.page(new Page<>(current, size),
                departmentService.getQueryWrapper(departmentQueryRequest));
        return ResultUtils.success(departmentPage);
    }


    /**
     * 直接获取所有部门信息
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<DepartmentVO>> getAllDepartment() {
        List<Department> departmentList = departmentService.list();
        List<DepartmentVO> departmentVOList = new ArrayList<>();
        for (Department department : departmentList) {
            DepartmentVO departmentVO = new DepartmentVO();
            BeanUtils.copyProperties(department, departmentVO);
            departmentVO.setUserName(userService.getById(department.getUserId()).getName());
            departmentVOList.add(departmentVO);
        }
        return ResultUtils.success(departmentVOList);
    }

    @GetMapping("/user/list")
    public BaseResponse<List<UserVO>> getAllUser() {
        List<User> userList = userService.list();
        List<UserVO> userVO = userService.getUserVOList(userList);
        return ResultUtils.success(userVO);
    }
}
